package com.microinvest.service.impl;
import com.microinvest.entity.Users;
import com.microinvest.dao.UserMapper;
import com.microinvest.service.RedisService;
import com.microinvest.service.UserService;
import com.microinvest.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final TokenServiceImpl tokenService;

    private final MailVerification scm;

    private final RedisService redisService;

    @Autowired
    public UserServiceImpl(UserMapper userMapper,TokenServiceImpl tokenService,MailVerification scm,RedisService redisService){
        this.userMapper=userMapper;
        this.tokenService=tokenService;
        this.scm=scm;
        this.redisService=redisService;
    }

    //进行注册服务
    @Override
    public Result registerUserService(Users users) {
        //判断注册的用户名以及邮箱是否存在
        Boolean exists=userMapper.existsByUsernameOrEmail(users.getUserName(),users.getEmail());
        if(exists){
            return Result.error("您的用户名或邮箱已被注册",null);
        }
        //验证邮箱格式是否正确
        Boolean emailFeasible= Validator.isValidEmail(users.getEmail());
        if(!emailFeasible){
          return Result.error("请输入正确的邮箱格式",null);
        }
        //判断密码规格是否正确
        Boolean passwordValidator= Validator.validateNewPassword(users.getPassword());
        if (!passwordValidator) {
            return Result.error("密码不符合要求，请确保密码长度大于8位且包含字母、数字和特殊字符");
        }
            //密码加密操作
            String encryptedPassword=SHA256Util.getSHA256String(users.getPassword());
            //加密后的值赋给password
            users.setPassword(encryptedPassword);
            userMapper.registerUsers(users);
            //返回userId
            int userId=userMapper.getUserIdFromUserName(users.getUserName());
            //注册userStockSummary
            userMapper.registerUserStockSummary(userId);
            //返回注册成功信息
            return Result.success("注册成功",null);
    }


    //使用旧密码修改密码
    @Override
    public Result<String> updateWithOldPwdService(String oldPassword, String newPassword) {
        // 通过当前线程的 Token 获取用户信息
        Map<String, String> map = ThreadLocalUtil.get();
        String userName = map.get("userName");

        // 比对旧密码是否正确
        boolean passwordCorrect = userMapper.comparePassword(userName, SHA256Util.getSHA256String(oldPassword));
        if (!passwordCorrect) {
            return Result.error("密码错误，请检查密码输入是否正确");
        }

        // 新密码校验复杂度
        Boolean passwordValidator= Validator.validateNewPassword(newPassword);
        if (!passwordValidator) {
            return Result.error("新密码不符合要求，请确保密码长度大于8位且包含字母、数字和特殊字符");
        }

        // 更新密码
        userMapper.updateWithOldPwd(SHA256Util.getSHA256String(newPassword));

        // 使当前 Token 失效
        String currentToken = (String) map.get("token");
        tokenService.invalidateToken(currentToken);

        // 清理线程变量
        ThreadLocalUtil.remove();
        return Result.success("密码修改成功，请重新登录");
    }

    //用户使用邮箱修改密码（第一步发送邮箱验证）
    @Override
    public Result updatePwdWithEmailStepOne(String email) {
        boolean Emailexist=userMapper.existsByUsernameOrEmail(null,email);
        //检查邮箱格式是否正确
        Boolean emailFeasible= Validator.isValidEmail(email);
        if(!emailFeasible){
            return Result.error("请输入正确的邮箱格式");
        }
        if(!Emailexist){
            return Result.error("未找到此邮箱");
        }
        //存在进行发送验证码操作
        //生成邮箱验证码
        String code= NumericCaptchaGenerator.generateNumericCaptcha();
        //发送验证码
        scm.sendMail(email,code);
        //将code存入redis，时效五分钟
        redisService.storeVerificationCode(email, code);
        return Result.success("验证码已发送");
    }

    //用户使用邮箱修改密码（第二步验证验证码正确）
    @Override
    public Result updatePwdWithEmailStepTwo(String email, String code) {
        Boolean codeRight=redisService.validateVerificationCode(email,code);
        if(!codeRight){
            return Result.error("验证码错误，请重试");
        }
        return Result.success("验证成功");
    }

    //用户使用邮箱修改密码（第三步修改密码）
    @Override
    public Result updatePwdWithEmailStepThree(String newPwd) {
        Boolean pwdValidator=Validator.validateNewPassword(newPwd);
        if(!pwdValidator){
            return Result.error(" 请输入正确的密码格式");
        }
        //加密密码后更新密码
        userMapper.updateWithOldPwd(SHA256Util.getSHA256String(newPwd));
        return Result.success("修改密码成功，请重新登录");
    }


}
